package com.atguigu.self.gulimall.ware.service.impl;

import com.atguigu.self.common.constant.WareConstant;
import com.atguigu.self.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.self.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.self.gulimall.ware.service.WareSkuService;
import com.atguigu.self.gulimall.ware.vo.MergeVo;
import com.atguigu.self.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.self.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.cert.TrustAnchor;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.self.common.utils.PageUtils;
import com.atguigu.self.common.utils.Query;

import com.atguigu.self.gulimall.ware.dao.PurchaseDao;
import com.atguigu.self.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.self.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0)
                        .or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        // 当合并没有选择采购单时，就创建一个新采购单
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // TODO  确认采购单状态是0和1才可以合并，(后面做)


        // 当已经选择采购单合并时, 只需要更新采购需求表的采购单id和status状态 / 更新 被关联采购单的最后更新时间
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = mergeVo.getItems().stream().map(detailId -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(detailId);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 更新 被关联采购单的最后更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        // 1、确定采购单状态是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(purchaseId -> {
            return this.getById(purchaseId);
        }).filter(purchaseEntity -> {
            return purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();

        }).map(purchaseEntity -> {
            // 2、符合条件的话修改采购单的状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());

        // 将修改状态后的采购单入库
        this.updateBatchById(purchaseEntities);

        // 3、修改采购需求(项)的状态（采购单id对应的采购需求修改）
        purchaseEntities.forEach(purchaseEntity -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(purchaseEntity.getId());
            List<PurchaseDetailEntity> detailEntities = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(purchaseDetailEntity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {


        Long doneVoId = purchaseDoneVo.getId(); // 采购单id

        // 2、更新采购项状态
        boolean flag = true; // 标志位，当当前左右采购项都完成时，采购单才完成，当有一个采购项没有完成则 flag = false 采购单状态就是有异常；
        List<PurchaseItemDoneVo> purchaseDoneVoItems = purchaseDoneVo.getItems();
        ArrayList<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo purchaseDoneVoItem : purchaseDoneVoItems) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (purchaseDoneVoItem.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(purchaseDoneVoItem.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3、将成功采购的进行更新(新增)商品库存数量（每一个采购项就是一个商品）
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(purchaseDoneVoItem.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(purchaseDoneVoItem.getItemId());
            updates.add(purchaseDetailEntity);


        }
        purchaseDetailService.updateBatchById(updates);
        // 1、更新采购单状态, 采购单的状态是根据采购项的状态决定的， 如果采购项有一个采购失败，那么当前采购单状态就是有异常
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVoId);
        int status = flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode();
        purchaseEntity.setStatus(status);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

}